package me.chan.netty.basic;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

@Slf4j
public class ClosedFutureClient {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                                        .group(eventLoopGroup)
                                        .channel(NioSocketChannel.class)
                                        .handler(new ChannelInitializer<NioSocketChannel>() {
                                            @Override
                                            protected void initChannel(NioSocketChannel sc) {
                                                sc.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG))
                                                            .addLast(new StringEncoder());
                                                // sc.pipeline().addLast(new StringEncoder());
                                            }
                                        }).connect("127.0.0.1", 8080)
                                        .sync();
        Channel channel = channelFuture.channel();
        // create a new thread to deal the input of System.in
        new Thread(()-> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.nextLine();
                if ("q".equalsIgnoreCase(line) ||
                        "q".equalsIgnoreCase(line.trim())) {
                    channel.close();
                    break;
                }

                channel.writeAndFlush(line);
            }

        }, "input-worker-1").start();


        // NOTE: how to do something after channel is closed?
        // m1: use channelFuture.sync()
        // m2: use ChannelFutureListener

        // m1
//        ChannelFuture closedFuture = channel.closeFuture();
//        closedFuture.sync();
//        log.debug("to do something after channel closed");

        // m2
        ChannelFuture closedFuture = channel.closeFuture();
        closedFuture.addListener((ChannelFuture cf) -> {
            log.debug("to do something after channel closed");
            eventLoopGroup.shutdownGracefully();
        });
    }
}
